/*
 * Package il.ac.biu.cs.grossmm.test.cpptest
 * File PublishProcessor.java
 * 
 * This is a part of presence service framework API. 
 * See javadoc for more information.
 *  
 * Copyright (C) 2006 Grossmann Mark
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
package il.ac.biu.cs.grossmm.tests.cpptest;

import static il.ac.biu.cs.grossmm.api.data.NodeTypeByInterface.*;
import static il.ac.biu.cs.grossmm.api.keys.PatternFactory.*;
import static il.ac.biu.cs.grossmm.api.keys.KeyFactory.*;
import static il.ac.biu.cs.grossmm.api.presence.BaseVocabulary.*;
import static il.ac.biu.cs.grossmm.api.presence.ResourceType.*;

import java.util.Random;

import il.ac.biu.cs.grossmm.api.OperationFailedException;
import il.ac.biu.cs.grossmm.api.data.Root;
import il.ac.biu.cs.grossmm.api.flow.DataProcessorBase;
import il.ac.biu.cs.grossmm.api.flow.NodeManipulator;
import il.ac.biu.cs.grossmm.api.flow.PublicationPoint;
import il.ac.biu.cs.grossmm.api.keys.Key;

public class PublishProcessor extends DataProcessorBase {

	PublicationPoint<FooPresence> pp;

	public PublishProcessor()
	{
		super("Publish processor");
	}

	@Override
	public void run()
	{
		try {
			pp =
				adm.createPublicationPoint(pattern(String.class, mandatory(
					RESOURCE_TYPE, PRESENCE)), nodeType(FooPresence.class),
					false, null);
		} catch (OperationFailedException e) {
			componentManager.abort(e);
			return;
		}

		started();

		Random r = new Random();

		while (!mustStop()) {
			int n = r.nextInt(5000);
			String alice = "Alice" + n;

			Key key = key(alice, entry(RESOURCE_TYPE, PRESENCE));

			try {
				Root<FooPresence> fooRoot = pp.createNode(key, true);

				if (fooRoot == null) {
					System.out.println("oops ");
					continue;
				}

				NodeManipulator man = pp.writeLock(fooRoot);
				man.setValue(fooRoot, FooPresence.ENTITY, alice);
				man.setValue(fooRoot, FooPresence.IS_ONLINE,
					System.currentTimeMillis() % 2 == 0);
				pp.writeUnlock(fooRoot);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}
}
